﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DHQGHN.Common;
using DHQGHN.DAL.BO.Admin;
using DHQGHN.DAL.Common;
using DHQGHN.MVC.Controllers;
using DHQGHN.PM0.Common.Attributes;
using DHQGHN.PM0.Models.Admin;
//using DHQGHN.DAL.Models.Admin;

namespace DHQGHN.PM0.Controllers.Admin
{
    public class TechnicalLevelController : BaseController
    {
        TechnicalLevelBO appBO;
        log4net.ILog logger = log4net.LogManager.GetLogger(typeof(TechnicalLevelController));
        // GET: /Application/
        public ActionResult Index(TechnicalLevelModel aModel = null, int pageIndex = 0, string sort = "AppId", string sortDir = "ASC", string currentId = null)
        {
            try
            {
                if (aModel == null) aModel = new TechnicalLevelModel();
                if (string.IsNullOrEmpty(currentId)) currentId = string.Empty;
                
                ViewBag.ActiveMenus = ViewBag.ActiveMenus == null ? new System.Collections.Hashtable() : ViewBag.ActiveMenus;
                ViewBag.ActiveMenus[13] = "active";
                ViewBag.ActiveMenus[23] = "active";
                aModel.DELETED = 2;
                var model = search(aModel, pageIndex, currentId, false);
                ViewBag.lstStatus = getListStatus();
                return View("~/Views/TechnicalLevel/TechnicalLevel.cshtml", model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }


        private IEnumerable<SelectListItem> getListStatus()
        {
            List<SelectListItem> lstItems = new List<SelectListItem>();
            lstItems.AddRange(new[]{
                new SelectListItem() { Text = "Tất cả", Value = "2" },
                new SelectListItem() { Text = "Đang sử dụng", Value = "0" },
                            new SelectListItem() { Text = "Không sử dụng", Value = "1" }
            });
            return new SelectList(lstItems, "Value", "Text");
        }

        [AjaxValidateAntiForgeryToken]
        public ActionResult reActive(string appId)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    TechnicalLevelModel model = new TechnicalLevelModel();
                    appBO = new TechnicalLevelBO();
                    bool result = appBO.reActive(appId);
                    if (result)
                    {
                        LogStream.Write(GetCurrentUserName(),
                           CommonData.AppName,
                           GetFunction(),
                           CommonData.GetListId(new string[] { appId }),
                           Resources.Localization.ActionActiveCaption + " - reActive");

                        return Json(JsonResponse.Json200("Khôi phục danh mục thành công!"));
                    }
                    else
                    {
                        return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        /// <summary>
        /// Hiển thị form thêm mới người dùng
        /// </summary>
        /// <param name="appId"></param>
        /// <returns></returns>
        [HttpPost]
        //[CustomAuthorize]
        //[ActionDescription(ActionCode = WebConst.ACTION_USER_ADD_CODE, ActionName = WebConst.ACTION_USER_ADD_NAME, GroupName = WebConst.USERS_GROUP_NAME, GroupCode = WebConst.USERS_GROUP_CODE, IsMenu = false)]
        public ActionResult actionPrepareCreateOrUpdateTechnicalLevel(string appId)
        {
            try
            {
                TechnicalLevelModel app = null;
                if (!String.IsNullOrEmpty(appId))
                {
                    appBO = new TechnicalLevelBO();
                    app = new TechnicalLevelModel(appBO.GetTechnicalLevelById(appId));
                    //u = unitOfWork.Users.GetById((int)userId);
                    //if (u != null)
                    //{
                    //    user = new UserModel(u);
                    //}
                }
                if (app == null)
                {
                    app = new TechnicalLevelModel()
                    {
                        NAME = string.Empty,
                        CODE = string.Empty,
                        DESCRIPTIONS = string.Empty,
                        TECHNICAL_LEVEL_ID = string.Empty,
                        DELETED = 0
                    };
                }
                if (Request.IsAjaxRequest())
                {
                    return PartialView("~/Views/TechnicalLevel/_TechnicalLevelModel.cshtml", app);
                }
                //RedirectToAction("ManageUsers", "Admin");
                return View(app);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [HttpPost]
        public ActionResult actionSearch(TechnicalLevelModel aModel = null, int pageIndex = 0, string sort = "AppId", string sortDir = "ASC", string currentId = null)
        {
            try
            {
                if (aModel == null) aModel = new TechnicalLevelModel();
                if (string.IsNullOrEmpty(currentId)) currentId = string.Empty;
                
                var model = search(aModel, pageIndex, currentId, false);
                return PartialView("~/Views/TechnicalLevel/_TechnicalLevelList.cshtml", model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        /// <summary>
        /// Thêm mới người dùng
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [AjaxValidateAntiForgeryToken]
        //[CustomAuthorize]
        [ValidateInput(false)]
        //[ActionDescription(ActionCode = WebConst.ACTION_USER_ADD_CODE, ActionName = WebConst.ACTION_USER_ADD_NAME, GroupName = WebConst.USERS_GROUP_NAME, GroupCode = WebConst.USERS_GROUP_CODE, IsMenu = false)]
        public ActionResult actionCreateOrUpdateTechnicalLevel(TechnicalLevelModel model)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    appBO = new TechnicalLevelBO();
                    bool result = appBO.createOrUpdateTechnicalLevel(model.toDALModel());
                    if (result)
                    {
                        LogStream.Write<TechnicalLevelModel>(GetCurrentUserName(),
                            CommonData.AppName,
                            GetFunction(),
                            Resources.Localization.ActionSaveUpdateCaption + " - actionCreateOrUpdateTechnicalLevel", model);

                        if (!(String.IsNullOrEmpty(model.TECHNICAL_LEVEL_ID) || string.IsNullOrWhiteSpace(model.TECHNICAL_LEVEL_ID)))
                        {
                            return Json(JsonResponse.Json200("Cập nhật thành công!"));
                        }
                        else
                        {
                            return Json(JsonResponse.Json200("Thêm mới thành công!"));
                        }
                    }
                    else
                    {
                        return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        [AjaxValidateAntiForgeryToken]
        public ActionResult actionDelete(string[] appId)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    appBO = new TechnicalLevelBO();
                    bool result = appBO.deleteTechnicalLevel(appId);
                    if (result)
                    {
                        LogStream.Write(GetCurrentUserName(),
                          CommonData.AppName,
                          GetFunction(),
                          CommonData.GetListId(appId),
                          Resources.Localization.ActionDeleteCaption + " - actionDelete");

                        return Json(JsonResponse.Json200("Xóa ứng dụng thành công!"));
                    }
                    else
                    {
                        return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        /// <summary>
        /// Kiem tra xem ten ung dung da ton tai chua
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="id"> </param>
        /// <returns></returns>
        //[CustomAuthorize]
        //[ValidateJsonAntiForgeryToken]
        //[ActionDescription(ActionCode = WebConst.ACTION_USER_ADD_CODE, ActionName = WebConst.ACTION_USER_ADD_NAME, GroupName = WebConst.USERS_GROUP_NAME, GroupCode = WebConst.USERS_GROUP_CODE, IsMenu = false)]
        public JsonResult CheckExistTechnicalLevelName(string Name, string TECHNICAL_LEVEL_ID)
        {
            try
            {
                var isExist = false;
                if (!string.IsNullOrEmpty(Name))
                {
                    TechnicalLevelModel appModel = new TechnicalLevelModel()
                    {
                        NAME = Name

                    };
                    var model = searchd(appModel, 0, string.Empty, true);

                    if (model.Data.Any())
                    {
                        var lstItem = model.Data;
                        foreach (TechnicalLevelModel app in lstItem)
                        {
                            if (!(String.IsNullOrEmpty(TECHNICAL_LEVEL_ID) || String.IsNullOrWhiteSpace(TECHNICAL_LEVEL_ID)))
                            {
                                //Neu chinh sua thong tin ung dung thi chi kiem tra nhung ung dung khac co trung khong
                                if (!Equals(app.TECHNICAL_LEVEL_ID, TECHNICAL_LEVEL_ID))
                                {
                                    isExist = true;
                                    break;
                                }
                            }
                            else
                            {
                                //Kiem tra truong hop them moi
                                isExist = true;
                                break;
                            }
                        }
                    }
                }
                if (isExist)
                {
                    return Json(Resources.Localization.TechnicalLevelNameExist);
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        /// <summary>
        /// Kiem tra xem Ma ung dung da ton tai chua
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="id"> </param>
        /// <returns></returns>
        //[CustomAuthorize]
        //[ValidateJsonAntiForgeryToken]
        //[ActionDescription(ActionCode = WebConst.ACTION_USER_ADD_CODE, ActionName = WebConst.ACTION_USER_ADD_NAME, GroupName = WebConst.USERS_GROUP_NAME, GroupCode = WebConst.USERS_GROUP_CODE, IsMenu = false)]
        public JsonResult CheckExistTechnicalLevelCode(string Code, string TECHNICAL_LEVEL_ID)
        {
            try
            {
                var isExist = false;
                if (!string.IsNullOrEmpty(Code))
                {
                    TechnicalLevelModel appModel = new TechnicalLevelModel()
                    {
                        CODE = Code
                    };
                    var model = searchd(appModel, 0, string.Empty, true);

                    if (model.Data.Any())
                    {
                        var lstItem = model.Data;
                        foreach (TechnicalLevelModel app in lstItem)
                        {
                            if (!(String.IsNullOrEmpty(TECHNICAL_LEVEL_ID) || String.IsNullOrWhiteSpace(TECHNICAL_LEVEL_ID)))
                            {
                                //Neu chinh sua thong tin ung dung thi chi kiem tra nhung ung dung khac co trung khong
                                if (!Equals(app.TECHNICAL_LEVEL_ID, TECHNICAL_LEVEL_ID))
                                {
                                    isExist = true;
                                    break;
                                }
                            }
                            else
                            {
                                //Kiem tra truong hop them moi
                                isExist = true;
                                break;
                            }
                        }
                    }
                }
                if (isExist)
                {
                    return Json(Resources.Localization.TechnicalLevelCodeExist);
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private DataPage<TechnicalLevelModel> search(TechnicalLevelModel aModel, int pageIndex, string currentId, bool compareEqual)
        {
            try
            {
                appBO = new TechnicalLevelBO();

                var DALModel = appBO.GetDynamicListPaging(aModel.toDALModel(), PageSize, pageIndex, compareEqual);
                var model = new DataPage<TechnicalLevelModel>();
                var lstItem = DALModel.Data;
                foreach (DHQGHN.DAL.Models.Admin.TechnicalLevelModel app in lstItem)
                {
                    model.Data.Add(new TechnicalLevelModel(app));
                }

                TechnicalLevelModel appModel = null;
                if (!String.IsNullOrEmpty(currentId) && model.Data.Count > 0)
                {
                    appModel = model.Data.Find(user => user.TECHNICAL_LEVEL_ID == currentId);
                    model.CustomData = appModel;
                }
                else
                {
                    model.CustomData = aModel;
                }
                if (model.Data.Count > 0)
                {
                    //Tao component phan trang
                    var pagNative = new Pagination
                    {
                        ActionName = "actionSearch",
                        ModelName = "TechnicalLevel",
                        CurrentPage = pageIndex,
                        InputSearchId = string.Empty,
                        TagetReLoadId = "app-list",

                    };
                    pagNative.TotalRows = model.Data[0].RecordCount;
                    pagNative.CurrentRow = model.Data.Count;
                    ViewBag.Pagination = pagNative;
                }
                return model;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private DataPage<TechnicalLevelModel> searchd(TechnicalLevelModel aModel, int pageIndex, string currentId, bool compareEqual)
        {
            try
            {
                appBO = new TechnicalLevelBO();

                var DALModel = appBO.GetDynamicListPagingd(aModel.toDALModel(), PageSize, pageIndex, compareEqual);
                var model = new DataPage<TechnicalLevelModel>();
                var lstItem = DALModel.Data;
                foreach (DHQGHN.DAL.Models.Admin.TechnicalLevelModel app in lstItem)
                {
                    model.Data.Add(new TechnicalLevelModel(app));
                }

                TechnicalLevelModel appModel = null;
                if (!String.IsNullOrEmpty(currentId) && model.Data.Count > 0)
                {
                    appModel = model.Data.Find(user => user.TECHNICAL_LEVEL_ID == currentId);
                    model.CustomData = appModel;
                }
                else
                {
                    model.CustomData = aModel;
                }
                if (model.Data.Count > 0)
                {
                    //Tao component phan trang
                    var pagNative = new Pagination
                    {
                        ActionName = "actionSearch",
                        ModelName = "TechnicalLevel",
                        CurrentPage = pageIndex,
                        InputSearchId = string.Empty,
                        TagetReLoadId = "app-list",

                    };
                    pagNative.TotalRows = model.Data[0].RecordCount;
                    pagNative.CurrentRow = model.Data.Count;
                    ViewBag.Pagination = pagNative;
                }
                return model;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private string GetFunction()
        {
            return "Danh mục trình độ chuyên môn, kỹ thuật - TechnicalLevelController";
        }
    }
}